import { execSync } from 'child_process';
import fs from 'fs';
import jszip from 'jszip'

/**
 * @type {ssh2.ConnectConfig}
 */
const LOCAL_PATH = "./build";

class BuildFrameConfig {
  framePath = "";
  gamePath = "";
  bundlePath = "";
};

const PackRec = async (zf, path) => {
  const fsDir = fs.opendirSync(path);
  let childDirent = fsDir.readSync();
  while (childDirent) {
    if (childDirent.isDirectory()) {
      let czf = zf.folder(childDirent.name);
      await PackRec(czf, path + childDirent.name + "/");
    }
    else {
      zf.file(childDirent.name, fs.readFileSync(path + childDirent.name));
    }
    childDirent = fsDir.readSync();
  }
  fsDir.closeSync();
};
const CompressRec = async (path) => {
  const fsDir = fs.opendirSync(path);
  let childDirent = fsDir.readSync();
  while (childDirent) {
    if (childDirent.isDirectory()) {
      await CompressRec(path + childDirent.name + "/");
    }
    else {
      if (childDirent.name.split(".")[1] == "png") {
        await execSync(`pngquant -f --ext .png --quality 10-90 --speed 1 "${path + childDirent.name}"`);
        console.log(`pngquant: 压缩图片"${path + childDirent.name}"`);
      }
    }
    childDirent = fsDir.readSync();
  }
  fsDir.closeSync();
};
//=======================================================================
let argvs = process.argv;
console.log("参数:", argvs.slice(2));
const BUILD_TARGET = argvs[2];
let config = new BuildFrameConfig();
if (!fs.existsSync("./buildFrame.json")) {
  fs.writeFileSync("./buildFrame.json", JSON.stringify(config));
}
else {
  let buf = fs.readFileSync("./buildFrame.json");
  let configStr = buf.toString();
  Object.assign(config, JSON.parse(configStr));
}

if (!BUILD_TARGET) {
  console.log("请输入参数: test/res");
  process.exit(0);
}

let framePathLocal = `${LOCAL_PATH}/${BUILD_TARGET}-frame`;

//删除旧文件
if (fs.existsSync(framePathLocal)) {
  let delStatment = `del /f /s /q ` + `"${framePathLocal}\\*.*" `.replaceAll("./", "").replaceAll("/", "\\");
  console.log("删除文件夹", framePathLocal);
  execSync(delStatment);
  execSync(`rd /s /q ` + `"${framePathLocal}"`.replaceAll("./", "").replaceAll("/", "\\"));
}

//复制所有文件。
let copyStatment = `xcopy /y /c /s /h /r ` + `"${LOCAL_PATH}\\web-mobile\\*.*" "${framePathLocal}\\" `.replaceAll("./", "").replaceAll("/", "\\");
console.log("复制文件", copyStatment);
execSync(copyStatment);

//复制模板文件
// xcopy /y /c /s /h /r "web-page\*.*" "build\web-mobile\"
copyStatment = `xcopy /y /c /s /h /r ` + `"web-page\\*.*" "${framePathLocal}\\" `.replaceAll("./", "").replaceAll("/", "\\");
console.log("复制文件", copyStatment);
execSync(copyStatment);

//一些路径
let framePath = config.framePath.replace("{{protocol}}", BUILD_TARGET == "test" ? "http://local." : "https://");
//修改index.html
let indexStr = fs.readFileSync(`${framePathLocal}/index.html`).toString();
indexStr = indexStr
  .replace("{{eruda}}", BUILD_TARGET == "test" ? `<script src="js/eruda.min.js"></script>` : "")
  .replace("{{wechat}}", BUILD_TARGET == "test" ? `<script src="js/eruda.min.js"></script>` : "")
  .replace("{{show_version}}", `<script> window.SHOW_VERSION=${BUILD_TARGET == "test" ? "true" : "false"}; </script>`)
  .replace("{{FramePath}}", framePath)
  .replace("{{GamePath}}", framePath + config.gamePath)
  .replace("{{BundlePath}}", framePath + config.bundlePath)
  ;
fs.writeFileSync(`${framePathLocal}/index.html`, indexStr);

//修改path/assets/main/index.js
let jsStr = fs.readFileSync(`${framePathLocal}/assets/main/index.js`).toString();
jsStr = jsStr.replace(/BUILD_TARGET:"(.+?)"/g, `BUILD_TARGET:"${BUILD_TARGET}"`);
fs.writeFileSync(`${framePathLocal}/assets/main/index.js`, jsStr);

//删除BUNDLE包
// del /f /s /q build\QiNiu\*.*
// rd /s /q build\QiNiu
let dir = fs.opendirSync(`${framePathLocal}/assets/`);
let dirent = dir.readSync();
while (dirent) {
  if (dirent.isDirectory()) {
    if (dirent.name != "internal" && dirent.name != "main") {
      let delStatment = `del /f /s /q ` + `"${framePathLocal}\\assets\\${dirent.name}\\*.*" `.replaceAll("./", "").replaceAll("/", "\\");
      console.log("删除文件夹", `${framePathLocal}\\assets\\${dirent.name}`);
      execSync(delStatment);
      execSync(`rd /s /q ` + `"${framePathLocal}\\assets\\${dirent.name}"`.replaceAll("./", "").replaceAll("/", "\\"));
    }
  }
  dirent = dir.readSync();
}
dir.closeSync();

//压缩
await CompressRec(`${framePathLocal}/`);
//打包
let zipPath = `${LOCAL_PATH}/${BUILD_TARGET}-frame.zip`;
{
  const zip = new jszip();
  await PackRec(zip, `${framePathLocal}/`);
  let content = await zip.generateAsync({ type: "nodebuffer", compression: "DEFLATE" });
  fs.writeFileSync(zipPath, content);
}
console.log("完成：", zipPath);
process.exit(0);